import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { message } from 'antd';
import md5 from 'blueimp-md5';
import React from 'react';
import { flushSync } from 'react-dom';
import { history, useModel } from 'umi';
import styles from './index.less';

import * as api from '@/services/account';

import defaultSettings from '../../../config/defaultSettings';

const Login: React.FC = () => {
  const { setInitialState } = useModel('@@initialState');

  let title = '';
  if (defaultSettings.title) {
    title = defaultSettings.title;
  }

  const fetchUserInfo = async (userInfo: API.AdminPassport) => {
    flushSync(() => {
      setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    });
  };

  const handleSubmit = async (reqModel: API.LoginRequest) => {
    // 登录
    reqModel.password = md5(reqModel.password);
    const result = await api.login(reqModel);
    if (result.success) {
      message.success('登录成功！');

      await fetchUserInfo(result.data);

      const urlParams = new URL(window.location.href).searchParams;
      const redirect = urlParams.get('redirect') || '/';

      history.push(redirect);
    } else if (result.errorMessage) {
      message.error(result.errorMessage);
    }
    return;
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg" />}
          title={title}
          subTitle=" "
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginRequest);
          }}
        >
          <ProFormText
            name="username"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入用户名!',
              },
            ]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
          </div>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
